var App=(function(){
	var $ = window.$ = window.app = function(){};
	$.init=(function(){
		
	})();
	//获取验证码效果
	//对应按钮需要是一个button 否者 disabled 效果会失效
	$.sendSMS=function (obj) {
		var i=50;
	    var html='剩余 ('+i+'s)';
	    var timer=window.setInterval(function () {
	    	i--;
	    	html='剩余( '+i+'s)';
	    	obj.innerHTML=html;
	    	if(i<=0){
	    		obj.disabled =false;
	    		obj.innerHTML='获取验证码';
	    		window.clearInterval(timer);
	    	}
	    },1000);
	    //obj.setAttribute('disabled','disabled');
	    obj.disabled =true;
	    obj.innerHTML=html;
	};
	//ajax
	/*
		使用：
		app.ajax({
			url:'/User/user_save',
			data:json_obj,
			callback:function(data){
				//这里写东西
			},errorback:function(a){
				
			}
		});
	*/
	$.ajax=function(settings){
		//var siteURL='http://192.168.0.106:8089/index.php/App';
		//var siteURL='http://192.168.31.208:8080/App/Index/get_index_info';
		var siteURL=window.localStorage.siteUrl;
		var json_str=JSON.stringify(settings.data);
		try{console.log('页面：'+plus.webview.currentWebview().id);}catch(e){}
		console.log(siteURL+settings.url);
		console.log(json_str);
		mui.ajax(siteURL+settings.url,{
			type:"post",
			data:{data:json_str},
			dataType:'json',
			async:true,
			timeout:60000,
			beforeSend:function (request) {
				 request.setRequestHeader("HUID", window.localStorage.UID);
				 request.setRequestHeader("HUUID", plus.device.uuid);
				 request.setRequestHeader("HPTYPE", plus.os.name);
				 request.setRequestHeader("HPBRAND", plus.device.model);
				 request.setRequestHeader("HTIME", (new Date()).getTime());
			},
			success:function (json) {
				try{
					if(typeof json.ECode!='undefined'&&typeof json.EMsg!='undefined'){}else{
						console.error('服务器端数据格式不正确');console.log(json);console.log(JSON.stringify(json));console.error('===stop ajax===');return;
					}
				}catch(e){
					console.error('服务器端数据格式不正确');console.log(json);console.log(JSON.stringify(json));console.error('===stop ajax===');return;
				}
				if(json.ECode==0){
					if(json.Data){
					if(json.EMsg.length>0){mui.toast(json.EMsg);}
					//这里有三个参数可以用
					settings.callback(json.Data,siteURL+settings.url);
					}else{console.log('无数据内容');console.log(JSON.stringify(json));}
				}else{
					if(settings.errorback){
						settings.errorback();
					}
					console.log('sql='+json.ESql);
					console.log(json.EMsg); 
					mui.toast(json.EMsg);
				}
			},error:function (a,b,c) {
				if(settings.errorback){
					settings.errorback(a);
				}
				console.log(a.response);
				console.log('请检查url地址:'+siteURL+settings.url);
				console.log('页面:'+plus.webview.currentWebview().id);
				mui.toast('网络请求失败,请打开wifi或流量['+a.response+']');
			}
		});
	}
	//是否为空字符串
	$.empty=function(str,len){
		if(len){len--;}else{len=0};
		try{
			if(typeof str !='string'){
				return true;
			}
			if(str.replace(/(^s*)|(s*$)/g, "").length <=len){
				return true;
			}
			return false;
		}catch(e){
			return true;
		}
		
	}
	$.emptyObj=function (e) {
		var t;  
	    for (t in e) {return false;}
	    return true;
	}
	//国内手机号码
	$.isPhone=function (phone) {
		try{
			var reg=/^((1[34578][0-9])+\d{8})$/i;
			if(!reg.test(phone)){
				return false;
			}
			return true;
		}catch(e){
			return false;
		}
	}
	//是否为邮箱
	$.isEmail=function (email) {
		try{
			var reg  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
			if(!reg.test(email)){
			return false;
			}
			return true;
		}catch(e){
			return false;
		}
	}
	//是否为数字
	$.intval=function (str) {
		try{
			if(!isNaN(str)){
				return str;
			}else{
				return 0;
			}
		}catch(e){
			return 0;
		}
	}
	//获取窗口高度
	$.windowHeight=function (res) {
		if(res){
			return Math.ceil(plus.screen.resolutionHeight-plus.navigator.getStatusbarHeight());
		}else{
			return 0;
		}
	}
	//获取窗口宽度
	$.windowWidth=function (res) {
		if(res){
			return Math.ceil(plus.screen.resolutionWidth*plus.screen.scale/3);
		}else{
			return 0;
		}
	}
	/*
	 	上传照片功能
		使用方法 
		app.getPhoto(function(imageData){
			document.querySelector('#box').src=imageData;
		},true);
		参数：callback 回调方法
		参数：compress 是否压缩，默认为压缩
	*/
	$.getPhoto=function(callback,compress,btn_type){
		compress=compress?compress:true;
		var btns = [{title: "拍照"}, {title: "从相册选择"}];
		if(btn_type=='only'){
			btns = [{title: "拍照"}];
		}
		//var btns - [{title:"nihao"},{title:"nihuai"}];
		plus.nativeUI.actionSheet({
			//title: "修改头像",
			cancel: "取消",
			buttons: btns
		}, function(btn) {
			switch (btn.index) {
				case 1:cameraImage();break;
				case 2:galleryImg();break;
				default:break;
			}
		});
		function cameraImage() {//相机
			plus.camera.getCamera().captureImage(function(e) {
				plus.io.resolveLocalFileSystemURL(e, function(entry) {
					var obj = entry.toLocalURL() + "?version=" + new Date().getTime();
					appendFile(obj,1);
				}, function(e) {
					console.log("读取拍照文件错误：" + e.message);
				});
			}, function(e) {}, {filename: "_doc/temp.jpg"});
		}
		function galleryImg() { //相册
			plus.gallery.pick(function(e) {
				plus.io.resolveLocalFileSystemURL(e, function(entry) {
					var obj = entry.fullPath+ "?version=" + new Date().getTime();
					appendFile(obj,2);//处理图片的地方
				}, function(e) {
					console.log("读取拍照文件错误：" + e.message);
				});
			}, function(e) {}, {filter: "image"})
		};
		function appendFile(path,imgType){
			var waiting=plus.nativeUI.showWaiting("图片处理中");
			var img = new Image();
		    img.src = path;
		    img.onload = function () {
		    	EXIF.getData(img, function() {
	            	Orientation=EXIF.getTag(img, 'Orientation');
	            	var that = this;
				    var w = that.width,h = that.height;
					var canvas = document.createElement('canvas');
			        var ctx = canvas.getContext('2d');
				    
		        	if(h <= w){
		        		if(compress){
							scale = w / h ;
							w = 480 || w;
							h = w/scale ;
						}
						if(Orientation==8||Orientation==6){
							canvas.setAttribute('width',h);
							canvas.setAttribute('height',w);
						}else{
							canvas.setAttribute('width',w);
							canvas.setAttribute('height',h);
						}
						
						var x=Math.ceil(w/2);
						var y=Math.ceil(h/2);
						if(Orientation==8){
							ctx.translate(y,x);
							ctx.rotate(-90*Math.PI/180);
							ctx.drawImage(that, -x,-y,w,h);
						}else if(Orientation==6){
							ctx.translate(y,x);
							ctx.rotate(90*Math.PI/180);
							ctx.drawImage(that, -x,-y,w,h);
						}else if(Orientation==3){
							ctx.translate(x,y);
							ctx.rotate(180*Math.PI/180);
							ctx.drawImage(that, -x,-y,w,h);
						}else{
							ctx.drawImage(that, 0,0,w,h);
						}
						
					}else if(w < h){
						if(compress){
							scale = h / w;
							h = 480 || h;
							w = h / scale;
						}
						
						canvas.setAttribute('width',w);
						canvas.setAttribute('height',h);
						ctx.drawImage(that,0,0,w,h);
					}
		        	var base64 = canvas.toDataURL('image/jpeg', 1 || 0.8 );   //1最清晰，越低越模糊。
		        	plus.nativeUI.closeWaiting(waiting);
		        	callback(base64);
		        });
		        
		    }
		};
		
	}
	
	//拓展参数 ，自定义分享样式
	//	var strObj = {
	//		id:xxx,
	//		ex:xxx,
	//	};
	//=======这是分割线=======
	//	var Share = {};
	//	Share.info={
	//		name:'专注科技分享',
	//		head_imge:"../images/100x100.png", //20kb 以内的png图片
	//		introduce:'专注科技',
	//		href:'http://www.baidu.com'
	//	};
	//	share(Share,strObj);
	//	share(Share);
    $.share = function(Share,strObj){
		var shares = {};
		init=function(){
			plus.share.getServices( function(s){
				shares={};
				for(var i in s){
					var t=s[i];
					shares[t.id]=t;
				}
				if(!!!strObj){
					var ids=[{id:"weixin",ex:"WXSceneSession"},{id:"weixin",ex:"WXSceneTimeline"},{id:"qq"},{id:"sinaweibo"}],
					bts = [{title:"发送给微信好友"},{title:"分享到微信朋友圈"},{title:"分享到QQ好友"},{title:"分享到新浪微博"}];
					plus.nativeUI.actionSheet({cancel:"取消",buttons:bts},
						function(e){var i = e.index;if(i > 0){shareAction(ids[i - 1].id, ids[i - 1].ex)}}
					);
				}else{
					shareAction(strObj.id,strObj.ex);
				}
			}, function(e){
				mui.toast( "获取分享服务列表失败："+e.message );
				return false;
			});
		};
		shareAction=function(id,ex){
			var s=null;
			if(!id||!(s=shares[id])){ 
				mui.toast( "无效的分享服务！" ); 
				return;
			}
			if(s.authenticated){
				shareMessage(s,ex);
			}else{
				s.authorize( function(){ 
					shareMessage(s,ex);
				},function(e){
					mui.toast( "认证授权失败："+e.code+" - "+e.message );
				});
			}
		};
		shareMessage=function(s,ex){
			var sharecount = 0;
			plus.nativeUI.showWaiting();
			setTimeout(function () {
				plus.nativeUI.closeWaiting();
			},2000);
			var msg = {
				extra:{
					scene: ex
				}
			};
			msg.href = Share.info.href;
			msg.title = Share.info.name;
			msg.content = Share.info.introduce;
			if(Share.info.head_imge.indexOf('ttp:')>0){
				msg.thumbs = [Share.info.head_imge];
			}else{
				var img = plus.io.convertAbsoluteFileSystem(plus.io.convertLocalFileSystemURL(Share.info.head_imge.replace('file://','')));
				msg.thumbs = [img];
			}
			if(sharecount > 0){
				msg.thumbs = ["img.src"];
			}
			if(s.id=='sinaweibo'){
				msg.content+=msg.href;
			}
			s.send(msg,function(){
				var strtmp = "分享到"+ s.description +"成功!";
				plus.nativeUI.toast('返回成功',{
					verticalAlign:'center'
				});
				sharecount = 0;
			},function(e){
				if(e.code == -2){
					plus.nativeUI.toast('已取消分享',{
						verticalAlign:'center'
					});
					sharecount = 0;
				}else if(e.code==-3||e.code==-8){
					if(++sharecount<2){
						shareMessage(s,ex);
					}else{
						sharecount = 0;
						plus.nativeUI.toast('分享失败',{
							verticalAlign:'center'
						});
					}
				}else{
					console.error('分享失败:' + JSON.stringify(e));
				}
			});
		};
		init();
	};
	
	//检查某个app是否存在
	/*
	 osname		:	系统类型（iOS,Android）
	 app_name	:	iOS系统下填写app名称，微信：weixin,QQ：qq,微博:weibo 
	 				Android系统下填写包名，百度地图：com.baidu.BaiduMap，高德地图：com.autonavi.minimap；微信：com.tencent.mm；QQ：com.tencent.qq
	 *
	 * 在ios中需要注意：在plus -> distribute -> apple 下添加urlschemewhitelist节点中，添加对应的包名。可以参考http://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/434
	 * */
	$.checkApp=function(os_name,app_name){
		if(os_name=='iOS'){
			var UIApplication = plus.ios.importClass("UIApplication");
			var NSURL = plus.ios.importClass("NSURL");
			
			var app = UIApplication.sharedApplication();
			var scheme = NSURL.URLWithString(app_name+"://");
			var install = app.canOpenURL(scheme);
			
			plus.ios.deleteObject(scheme);
			plus.ios.deleteObject(app);
			
			return install;
		}
		if(os_name=='Android'){
			var install=false;
			try {
		        var main = plus.android.runtimeMainActivity();
		        var packageManager = main.getPackageManager();
		        var PackageManager = plus.android.importClass(packageManager);
		        var packageInfo = packageManager.getPackageInfo(app_name, PackageManager.GET_ACTIVITIES);
		        if (packageInfo) {
					install=true;
		        }
		        return install;
		   	}catch(e){}
		   	return install;
		}
	}
	//base64文件转二进制文件
	$.strToBlob=function(imageData){
		var dataURItoBlob=function(dataURI){
			 // convert base64 to raw binary data held in a string 
	        var byteString,mimestring 
	        if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
	            byteString = atob(dataURI.split(',')[1])
	        } else {
	            byteString = decodeURI(dataURI.split(',')[1])
	        }
	        mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]
	        var content = new Array();
	        for (var i = 0; i < byteString.length; i++) {
	            content[i] = byteString.charCodeAt(i)
	        }
	        return new Blob([new Uint8Array(content)], {type: mimestring})
		}
		var _blob = dataURItoBlob1(imageData);
		var _url = window.URL.createObjectURL(_blob);//这里会有浏览器兼容问题
		//bof 兼容处理方法
		/*
		function getObjectURL(file) {
	    	var url = null ; 
	    	if (window.createObjectURL!=undefined) { // basic
	    		url = window.createObjectURL(file) ;
	    	} else if (window.URL!=undefined) { // mozilla(firefox)
	        	url = window.URL.createObjectURL(file) ;
	    	} else if (window.webkitURL!=undefined) { // webkit or chrome
	        	url = window.webkitURL.createObjectURL(file) ;
	      	}
	      	return url ;
	    }
		 */
		//eof 兼容处理方法
		return {'blob':_blob,'url':_url};
	}
	/*
	 判断数组中是否存在
	 * search：关键词
	 * array：数组
	 * */
	$.in_array=function (search,array){
	    for(var i in array){
	        if(array[i]==search){
	            return true;
	        }
	    }
	    return false;
	}
	/*
	 拨打电话通用方法
	 * phone	:	电话号码
	 * */
	$.give_phone=function(phone){
		mui.confirm('您将要拨打电话\n'+phone,'温馨提示',['确定','取消'],function (e) {
			if(e.index==0){
				plus.device.dial(phone,false);
			}else{}
		});
	}
	//判断网络状态 感谢qq群415857753里“耀³”的贡献
	$.on_net_change=function(){
		var nt = plus.networkinfo.getCurrentType();
		switch(nt) {
			case plus.networkinfo.CONNECTION_ETHERNET:
				$.toast("已经连接到有线网络");
				break;
			case plus.networkinfo.CONNECTION_WIFI:
				$.toast("已经连接wifi");
				break;
			case plus.networkinfo.CONNECTION_CELL2G:
				$.toast('已经连接到2G网络');
				break;
			case plus.networkinfo.CONNECTION_CELL3G:
				$.toast("已经连接3G网络");
				break;
			case plus.networkinfo.CONNECTION_CELL4G:
				$.toast("已经连接蜂窝网络");
				break;
			default:
				$.toast("无网络连接");
				break;
		}
	}
	
})();

